﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrinterMonitorSvc.Common
{
    /// <summary>
    /// Json帮助类(Newtonsoft.Json)
    /// </summary>
    public static class JsonHelper
    {
        #region 将对象序列化为字符串
        /// <summary>
        /// 将对象序列化为字符串
        /// </summary>
        /// <typeparam name="TEntity">序列化的对象类型</typeparam>
        /// <param name="obj">序列化的对象</param>
        /// <returns>字符串</returns>
        public static string ConvertJson<TEntity>(TEntity obj)
        {
            return obj is string ? obj.ToString() : JsonConvert.SerializeObject(obj);
        }
        #endregion

        #region 将json值转为实体对象
        /// <summary>
        /// 将json值转为实体对象
        /// </summary>
        /// <typeparam name="TEntity">对象类型</typeparam>
        /// <param name="value">json值</param>
        /// <returns>对象</returns>
        public static TEntity ConvertObj<TEntity>(string value)
        {
            if (null == value)
            {
                return default(TEntity);
            }
            if (typeof(TEntity) == typeof(string))
            {
                return (TEntity)(object)value;
            }
            return JsonConvert.DeserializeObject<TEntity>(value);
        }
        #endregion

    }
}
